package com.fx.ruankao.controller;

import com.fx.ruankao.entity.User;
import com.fx.ruankao.service.UserService;
import com.fx.ruankao.utils.Result;
import com.fx.ruankao.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 用户控制器 - 管理端
 */
@RestController
@RequestMapping("/api/admin/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 新增用户
     */
    @PostMapping
    public Result insert(@RequestBody User user) {
        try {
            int result = userService.insert(user);
            if (result > 0) {
                return Result.success("新增用户成功");
            } else {
                return Result.error("新增用户失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID删除用户
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Long id) {
        try {
            if (id == null || id <= 0) {
                return Result.error("用户ID无效");
            }
            int result = userService.deleteById(id);
            if (result > 0) {
                return Result.success("删除用户成功");
            } else {
                return Result.error("删除用户失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        try {
            int result = userService.update(user);
            if (result > 0) {
                return Result.success("更新用户成功");
            } else {
                return Result.error("更新用户失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Long id) {
        try {
            if (id == null || id <= 0) {
                return Result.error("用户ID无效");
            }
            User user = userService.selectById(id);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.error("未找到用户");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有用户
     */
    @GetMapping
    public Result selectAll() {
        try {
            List<User> users = userService.selectAll();
            return Result.success(users);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        try {
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            if (user != null) {
                // 生成token等逻辑
                return Result.success(user, "登录成功");
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody PasswordRequest passwordRequest) {
        try {
            if (passwordRequest == null) {
                return Result.error("请求参数不能为空");
            }
            if (passwordRequest.getUserId() == null || passwordRequest.getUserId() <= 0) {
                return Result.error("用户ID无效");
            }
            if (passwordRequest.getOldPassword() == null || passwordRequest.getOldPassword().trim().isEmpty()) {
                return Result.error("旧密码不能为空");
            }
            if (passwordRequest.getNewPassword() == null || passwordRequest.getNewPassword().trim().isEmpty()) {
                return Result.error("新密码不能为空");
            }
            boolean result = userService.changePassword(
                passwordRequest.getUserId(), 
                passwordRequest.getOldPassword(), 
                passwordRequest.getNewPassword()
            );
            if (result) {
                return Result.success("修改密码成功");
            } else {
                return Result.error("旧密码错误或修改失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 重置密码
     */
    @PostMapping("/resetPassword/{userId}")
    public Result resetPassword(@PathVariable Long userId) {
        try {
            if (userId == null || userId <= 0) {
                return Result.error("用户ID无效");
            }
            // 生成随机强密码
            String randomPassword = generateRandomPassword();
            boolean result = userService.resetPassword(userId, randomPassword);
            if (result) {
                // 实际应用中应通过邮件或短信通知用户
                return Result.success("重置密码成功，新密码为：" + randomPassword);
            } else {
                return Result.error("重置密码失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 生成随机强密码
     * @return 随机密码
     */
    private String generateRandomPassword() {
        // 密码字符集
        String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lower = "abcdefghijklmnopqrstuvwxyz";
        String digits = "0123456789";
        String special = "!@#$%^&*()-_=+[]{}|;:,.<>?";
        String chars = upper + lower + digits + special;
        
        // 生成随机密码
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(12);
        
        // 至少包含一个大写字母
        sb.append(upper.charAt(random.nextInt(upper.length())));
        // 至少包含一个小写字母
        sb.append(lower.charAt(random.nextInt(lower.length())));
        // 至少包含一个数字
        sb.append(digits.charAt(random.nextInt(digits.length())));
        // 至少包含一个特殊字符
        sb.append(special.charAt(random.nextInt(special.length())));
        
        // 填充剩余字符
        for (int i = 4; i < 12; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        // 打乱顺序
        return shuffleString(sb.toString());
    }
    
    /**
     * 打乱字符串顺序
     * @param input 输入字符串
     * @return 打乱后的字符串
     */
    private String shuffleString(String input) {
        List<Character> characters = new ArrayList<>();
        for (char c : input.toCharArray()) {
            characters.add(c);
        }
        Collections.shuffle(characters);
        StringBuilder output = new StringBuilder(input.length());
        for (char c : characters) {
            output.append(c);
        }
        return output.toString();
    }
    
    /**
     * 登录请求参数
     */
    public static class LoginRequest {
        private String username;
        private String password;
        
        // getter和setter
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    /**
     * 密码修改请求参数
     */
    public static class PasswordRequest {
        private Long userId;
        private String oldPassword;
        private String newPassword;
        
        // getter和setter
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
    

}